import React, { Component } from 'react'
import { Button, Form, Input, Space, InputNumber, Tooltip, message } from 'antd'
import { QuestionCircleOutlined } from "@ant-design/icons";
import TheTable from '@/components/TheTable'
import TheButton from '@/components/TheButton'
import TheDialog from '@/components/TheDialog'
import TheUpload from '@/components/TheUpload'
import TheImage from '@/components/TheImage'
import TheQueryForm from '@/components/TheQueryForm';
import store from "@/store/store"
import _ from 'lodash'
import './style/style.less'
import { knowledgeClassifyPage, knowledgeClassifyDel, knowledgeClassifyAdd, knowledgeClassifyEdit, knowledgeClassifyView, knowledgeClassifySearch } from '@/request/petCircleUtil/category';

let fatherBtnIndex = ''
let sonBtnIndex = ''
class Category extends Component {
  constructor() {
    super()
    this.queryFormRef = React.createRef()
    this.state = {
      form_show: false,
      columns1: [
        {
          title: '一级类目',
          dataIndex: 'knowledgeClassifyName',
          key: 'knowledgeClassifyName',
        },
        {
          title: '排序',
          dataIndex: 'sorted',
          key: 'sorted',
          width:200,
          filterDropdown: true, // 自定义的列筛选功能，我们占位为信息提示Icon的位置
          filterIcon: () => {
            return (
              <Tooltip placement="top" title={() => { return <div> 备注：数字越小排名越靠前 </div> }}  >
                <QuestionCircleOutlined style={{ fontSize: '20px' }} />
              </Tooltip>
            );
          },
          onCell: () => {
            return {
              style: {
                padding: 0
              },
            };
          },
          render: (text, record, index) => {
            return (
              <div style={{ display: 'flex', alignItems: 'center', }}
                onClick={(e) => e.stopPropagation()}
              >
                <InputNumber ref={(ref) => this["onFocus_" + index] = ref} min={1} max={9999} precision={0} value={text}
                  onFocus={() => {
                    this["tab_btn_" + index].disabled = false
                    if (fatherBtnIndex !== index && fatherBtnIndex !== "") {
                      this["tab_btn_" + fatherBtnIndex].disabled = true
                    }
                    fatherBtnIndex = index
                    this.btnStatus()
                  }
                  }
                  onBlur={() => {
                    if (fatherBtnIndex !== index) {
                      this["tab_btn_" + index].disabled = true
                    }
                  }}
                  onChange={this.valueInput}
                />

                <div onClick={(e) => this.sortValue1(this["tab_btn_" + index].disabled, record.knowledgeClassifyId)}><Button ref={(ref) => this["tab_btn_" + index] = ref} disabled={true} style={{ marginLeft: '20px' }} type="primary" > 确定 </Button></div>
              </div>
            )
          }
        },
        {
          title: '别名',
          dataIndex: "alias",
          key: "alias",
        },
        {
          title: '操作',
          render: (text, record) => {
            return (
              <>
                <TheButton haspermi={['petCircleUtil:category:add2']} onClick={(e) => this.addDialog(e, 2, record)}>
                  新增
                </TheButton>
                <TheButton haspermi={['petCircleUtil:category:edit1']} onClick={(e) => this.editDialog(e, 1, record)}>
                  修改
                </TheButton>
                <TheButton haspermi={['petCircleUtil:category:delete1']} onClick={(e) => this.delConfirm(e, record, '一')}>
                  删除
                </TheButton>
              </>
            )
          },
        },
      ],
      columns2: [
        {
          title: '二级类目',
          dataIndex: 'knowledgeClassifyName',
          key: 'knowledgeClassifyName',
        },
        {
          title: '排序',
          dataIndex: 'sort',
          key: 'sort',
          width:200,

          render: (text, record, index) => {
            return (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <InputNumber min={1} max={9999} precision={0} value={record.sorted} onChange={this.valueInput} onFocus={() => {
                  this["tab_btns_" + index].disabled = false
                  if (sonBtnIndex !== index && sonBtnIndex !== "") {
                    this["tab_btns_" + sonBtnIndex].disabled = true
                  }
                  this.btnFatherStatus()
                  sonBtnIndex = index
                }
                }
                  onBlur={() => {
                    if (sonBtnIndex !== index) {
                      this["tab_btns_" + index].disabled = true
                    }
                  }} />
                <div onClick={() => this.sortValue2(this["tab_btns_" + index].disabled, record.knowledgeClassifyId)}><Button ref={(ref) => this["tab_btns_" + index] = ref} disabled={true} style={{ marginLeft: '20px' }} type="primary" > 确定 </Button></div>
              </div>
            )
          }
        },
        {
          title: '别名',
          dataIndex: "alias",
          key: "alias",
        },
        {
          title: '类目图片',
          dataIndex: 'picture',
          key: 'picture',
          render: (text, record) => {
            return <TheImage src={text} width={50} height={50} />
          },
        },
        {
          title: '操作',
          render: (text, record) => {
            return (
              <>
                <TheButton haspermi={['petCircleUtil:category:edit2']} onClick={(e) => this.editDialog(e, 2, record)}>
                  修改
                </TheButton>
                <TheButton haspermi={['petCircleUtil:category:delete2']} onClick={(e) => this.delConfirm(e, record, '二')}>
                  删除
                </TheButton>
              </>
            )
          },
        },
      ],
      dataSource: {
        1: [], // 一级类目
        2: [], // 二级类目
      },
      nowLevel: '', // 当前选择的类目等级
      visible: false, //新增修改弹窗
      title: '',
      level: '1', // 层级(初始层级1)
      sourceId: '', // 上级类目id
      addId: '', // 新增的上级id
      fileList: [],
      changeName: true,
      knowledgeClassifyId: '', // 类目id
      options: [],
      searchOption: [
        {
          field: 'knowledgeClassifyId', label: '类目', placeholder: '可输入一级、二级类目名称', required: false, rules: [], type: 'Cascader', defaultValue: '', option: []
        },
      ],
      sorted: '', // 排序
      queryForm: {},
      changeFlag: false,
    }
  }
  componentDidMount() {
    this.getData()
    this.getSearch()
  }
  // 知识库类目列表
  getData = async () => {
    let { level, sourceId, changeName, dataSource } = this.state
    if (!changeName) return
    let res = await knowledgeClassifyPage({ level, sourceId })
    if (res.code === 0 && res.data) {
      this.setState({
        dataSource: {
          ...dataSource,
          [`${level}`]: res.data,
        },
        knowledgeClassifyId: res.data.knowledgeClassifyId
      })
    }
  }
  getDataFather = async (value) => {
    let { level } = this.state
    const knowledgeClassifyId = value === undefined ? [] : value.knowledgeClassifyId ?? []
    this.setState({
      queryForm: { knowledgeClassifyId }
    })
    let arr = [1, 2], dataSource = {}, sourceId = ''
    let params = { sourceId, level }
    arr.forEach(async (v, index) => {
      params.level = v
      params.knowledgeClassifyId = knowledgeClassifyId[index] ?? ''
      await knowledgeClassifyPage({ ...params }).then((res) => {
        if (res.code === 0) {
          if (knowledgeClassifyId.length !== 2 && index === 1) {
            dataSource[v] = []
          }
          else {
            dataSource[v] = res.data
          }
          // if (knowledgeClassifyId.length > 1) {
          //   sourceId = res.data[0].sourceId
          // }
        }
      })
      this.setState({
        dataSource,
        sourceId
      })
    })
  }
  // 知识库类目树形结构
  getSearch = async () => {
    let { searchOption } = this.state
    let res = await knowledgeClassifySearch()
    if (res.code === 0) {
      let arr = res.data.map(item => {
        return {
          value: item.knowledgeClassifyId,
          label: item.knowledgeClassifyName,
          children: item.children ? item.children.map(v => {
            return {
              value: v.knowledgeClassifyId,
              label: v.knowledgeClassifyName,
            }
          }) : null
        }
      })
      searchOption[0].option = arr
      this.setState({
        searchOption
      })
    }
  }
  // 搜索
  onFormSearch(values) {
    this.setState(() => {
      this.getDataFather(values)
    })
  }
  // 重置搜索
  onReset() {
    if ("knowledgeClassifyId" in this.state.queryForm && this.state.queryForm.knowledgeClassifyId.length) {
      this.setState({
        sourceId: ''
      })
    }
    this.setState({
      queryForm: {}
    }, () => {
      this.getDataFather()
    })
  }
  // 排序输入框
  valueInput = (e) => {
    this.setState({ sorted: e, changeFlag: true })
  }
  // 修改排序
  sortValue1 = async (disabled, id) => {
    const { sorted } = this.state
    //如果没有修改 就不调用
    if (!this.state.changeFlag) {
      return message.warning("您没有做任何修改")
    }
    this.setState({ changeFlag: false, sorted: this.state.sorted })
    if (!disabled) {
      let res = await knowledgeClassifyEdit({ knowledgeClassifyId: id, sorted })
      if (res.code === 0) {
        message.success("一级类目排序修改成功")
        this.getDataFather(this.state.queryForm)
      }
    }
  }
  sortValue2 = async (disabled, id) => {
    const { sorted } = this.state
    if (!this.state.changeFlag) {
      return message.warning("您没有做任何修改")
    }
    this.setState({ changeFlag: false })
    this.setState({ sorted: this.state.sorted })
    if (!disabled) {
      let res = await knowledgeClassifyEdit({ knowledgeClassifyId: id, sorted })
      if (res.code === 0) {
        message.success("二级类目排序修改成功")
        this.getData()
      }
    }
  }
  // 查看知识库类目详情
  getView = async (level, knowledgeClassifyId) => {
    let res = await knowledgeClassifyView({ knowledgeClassifyId })
    if (res.code === 0 && res.data) {
      this.formRef.setFieldsValue({ ...res.data }) // 表单回显数据
      this.setState({ knowledgeClassifyId: res.data.knowledgeClassifyId, sourceId: res.data.sourceId }) // 详情类目id
    }
  }
  // 点击一级类目显示对应的二级类目
  handleClick = (value, index) => {
    const { level, knowledgeClassifyId } = value
    const { changeName, dataSource, sourceId } = this.state
    if (!changeName) return
    if (parseInt(level) === 1 && sourceId !== knowledgeClassifyId) {

      this.setState(
        {
          level: 2, //层级
          sourceId: knowledgeClassifyId, //上级类目id
          dataSource: {
            ...dataSource, // 表格数据
          },
        },
        () => {
          this.getData()
          this.btnStatus()
          // this.btnFatherStatus()
          this["tab_btn_" + index].disabled = false
        }
      )
    }
  }
  // 点击表格切换类名
  setRowClassName = (record) => {
    const { level } = record
    if (parseInt(level) === 1) {
      return record.knowledgeClassifyId === this.state.sourceId ? 'active-row' : ''
    }
  }
  // 图片回显
  getFileResult = (file) => {
    let picture = file
      .map((v) => {
        if (v.response) {
          if (v.response.code === 0 && v.response.data) {
            return v.response.data
          }
        }
      })
      .join(',')
    this.formRef.setFieldsValue({ picture })
  }
  // 新增类目
  addDialog = (e, level, value) => {
    e.stopPropagation()
    this.setState({
      nowLevel: level, // 当前选择的类目级别
      title: '新增分类',
      visible: true,
      addId: value.knowledgeClassifyId,
      changeName: false,
    })
  }
  // 修改类目
  editDialog = (e, level, value) => {
    e.stopPropagation()
    let fileList = [
      {
        uid: 1,
        name: 'image',
        status: 'done',
        url: value.picture,
      },
    ]
    this.setState({
      title: '修改分类',
      visible: true,
      editValue: value,
      fileList,
      nowLevel: level,
      changeName: false,
      knowledgeClassifyId: value.knowledgeClassifyId
    }, () => {
      this.getView(level, value.knowledgeClassifyId)
    })
  }
  // 关闭弹窗
  closeDialog = () => {
    this.setState({
      nowLevel: '', // 当前
      title: '',
      visible: false,
      fileList: [],
      changeName: true,
    })
  }
  // 删除类目
  delConfirm = (e, value, str) => {
    this.setState({ changeName: false })
    let { knowledgeClassifyId, level, sourceId } = value
    e.stopPropagation()
    React.$confirm({
      title: `您确认删除此${str}级分类吗？`,
      onOk: async () => {
        let res = await knowledgeClassifyDel({ knowledgeClassifyId })
        if (res.code === 0) {
          this.setState(
            {
              level,
              sourceId: sourceId || '',
              changeName: true,
            },
            () => {
              React.$message({
                type: 'info',
                content: '删除成功',
              })
              this.getData()
            }
          )
        } else {
          this.setState({
            changeName: true,
          })
        }
      },
      onCancel: () => {
        this.setState({
          changeName: true,
        })
      },
    })
  }
  // 保存新建/修改类目
  dialogSave = async (values) => {
    const { nowLevel, addId, title, sourceId, knowledgeClassifyId } = this.state
    console.log(knowledgeClassifyId);
    if (title === '新增分类') {
      let res = await knowledgeClassifyAdd({
        level: nowLevel,
        sourceId: addId || '0',
        ...values,
      })
      if (res.code === 0) {
        this.setState(
          {
            level: nowLevel,
            sourceId: addId,
          },
          async () => {
            await this.closeDialog()
            React.$message({
              type: 'info',
              content: '新增成功',
            })
            await this.getData()
          }
        )
      }
    }
    if (title === '修改分类') {
      let res = await knowledgeClassifyEdit({ knowledgeClassifyId, ...values })
      console.log(sourceId);
      if (res.code === 0) {
        this.setState(
          {
            level: nowLevel,
            sourceId: sourceId || '',
          },
          async () => {
            await this.closeDialog()
            React.$message({
              type: 'info',
              content: '修改成功',
            })
            await this.getData()
          }
        )
      }
    }
  }
  btnStatus() {
    let { dataSource } = this.state
    dataSource[2].map((item, index) => this["tab_btns_" + index].disabled = true)
  }
  btnFatherStatus() {
    let { dataSource } = this.state
    dataSource[1].map((item, index) => this["tab_btn_" + index].disabled = true)
  }

  render() {
    const { dataSource, visible, title, nowLevel, fileList, form_show, searchOption, } = this.state
    return (
      <div className="p-layout-box">
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={!form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
        </TheQueryForm>
        <div style={{ display: 'flex' }}>
          <TheButton haspermi={['petCircleUtil:category:add1']} type="default" size="middle" onClick={(e) => this.addDialog(e, 1, '')}>
            新增一级类目
          </TheButton>

        </div>
        <div className="p-layout-content mall-category-second">
          {_.map(dataSource, (v, i) => {
            this.state.type = i
            return (
              <TheTable
                onRow={(record, index) => {
                  return {
                    onClick: () => this.handleClick(record, index),
                  }
                }}
                scroll={{ y: '75vh' }}
                rowClassName={this.setRowClassName}
                columns={this.state[`columns${i}`]}
                dataSource={v}
              />
            )
          })}
        </div>
        <TheDialog
          width={400}
          visible={visible}
          title={title}
          footer={null}
          handleCancel={this.closeDialog}>
          <Form
            ref={(ref) => (this.formRef = ref)}
            onFinish={this.dialogSave}
            labelCol={{ span: 6 }}
          >
            <Form.Item
              name="knowledgeClassifyName"
              label="名称"
              rules={[{ required: true }]}>
              <Input maxLength={5} placeholder="请输入名称" />
            </Form.Item>
            <Form.Item
              name="alias"
              label="别名">
              <Input placeholder="请输入别名" />
            </Form.Item>
            {(nowLevel === 2) && (
              <Form.Item
                name="picture"
                label={'分类图片'}
                rules={[{ required: true }]}>
                <TheUpload
                  len={1}
                  fileList={fileList}
                  getFileResult={this.getFileResult}
                />
              </Form.Item>
            )}
            <Form.Item
              name="sorted"
              label="排序"
              rules={[{ required: true }]}
            >
              <InputNumber placeholder="请输入排序" min={1} max={9999} onChange={(value) => {
                console.log('changed', value);
              }} />
            </Form.Item>
            <Form.Item>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'flex-end',
                  marginBottom: -30,
                }}>
                <Space>
                  <Button onClick={this.closeDialog}>取消</Button>
                  <Button type="primary" htmlType="submit">
                    保存
                  </Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </TheDialog>
      </div>
    )
  }
}

export default Category
